<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src='lib/webgl-utils.js'></script>
    <script src='lib/webgl-debug.js'></script>
    <script src='lib/cuon-utils.js'></script>
</head>
<body onload="main()">
<canvas id="mybox" width="500" height="500">
    请更换新版浏览器查看效果!
</canvas>
<script>
    let VSHADER_SOURCE=`
    attribute vec4 a_position;
    void main(){
        gl_Position=a_position;
        gl_PointSize=10.0;
    }`;
    let FSHADER_SOURCE=`
    precision mediump float;
    uniform vec4 u_fragColor;
    void main(){
        gl_FragColor=u_fragColor;
    }`;


    let g_points=[];
    let g_fragColor=[];

    function main(){
        let canvas=document.getElementById('mybox')
        let gl=getWebGLContext(canvas)
        if(!gl){
            console.log('WebGl 获取失败');
            return;
        }
        if(!initShaders(gl,VSHADER_SOURCE,FSHADER_SOURCE)){
            console.log('初始化shaders失败');
            return;
        }
        let a_position=gl.getAttribLocation(gl.program,'a_position');
        let u_fragColor=gl.getUniformLocation(gl.program,'u_fragColor');
        /*console.log(u_fragColor)
        console.log(a_position)*/
        if(a_position<0){
            console.log('a_position is not exist');
            return;
        }
        if(u_fragColor<0){
            console.log('u_fragColor is not exist');
            return;
        }
        gl.clearColor(0.0,0.0,0.0,1.0);
        gl.clear(gl.COLOR_BUFFER_BIT);
        canvas.onmousedown=e=>{
            changePointColor(e,canvas,gl,a_position,u_fragColor);
        }


    }

    function changePointColor(e,canvas,gl,a_position,u_fragColor){
        let x=e.clientX;
        let y=e.clientY;

        x-rect.left-(canvas.width/2)/a=canvas.width/2
        canvas.height/2-(y-rect.top)

        let rect=canvas.getBoundingClientRect();
        let posX=(x-rect.left-(canvas.width/2))/(canvas.width/2);
        let posY=(canvas.height/2-(y-rect.top))/(canvas.height/2);
        g_points.push([posX,posY]);
        if(posX>=0.0 && posY>=0.0){
            g_fragColor.push([1.0,0.0,0.0,1.0]);
        }else if(posX<0.0 && posY<0.0){
            g_fragColor.push([0.0,1.0,0.0,1.0]);
        }else if(posX>=0.0 && posY<=0){
            g_fragColor.push([0.0,0.0,1.0,1.0]);
        }else{
            g_fragColor.push([1.0,1.0,1.0,1.0]);
        }
        gl.clear(gl.COLOR_BUFFER_BIT);

        g_points.forEach((value,index)=>{
            gl.vertexAttrib3f(a_position,value[0],value[1],0.0);
            let fragColor=g_fragColor[index]
            gl.uniform4f(u_fragColor,fragColor[0],fragColor[1],fragColor[2],fragColor[3]);
            gl.drawArrays(gl.POINTS,0,1);

        })
    }
</script>

</body>
</html>